﻿using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Primitives;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ZhCun.WebUtils.Configs;
using ZhCun.Utils.Helpers;

namespace ZhCun.WebUtils
{
    public static class ExHttpContext
    {
        public static string GetToken(this HttpContext context)
        {
            var token = GetHeader(context, CommonConfig.THIS.TokenName);
            if (token.IsEmpty())
            {
                token = GetCookie(context, CommonConfig.THIS.TokenName);
            }
            return token;
        }

        public static string GetHeader(this HttpContext context, string headerName)
        {
            if (context.Request.Headers.TryGetValue(headerName, out StringValues value))
            {
                return value.First();
            }
            else
            {
                return null;
            }
        }

        public static string GetCookie(this HttpContext context, string cookieName)
        {
            context.Request.Cookies.TryGetValue(cookieName, out string value);
            return value;
        }

        public static string SetCookie(this HttpContext context, string cookieName, string value, DateTime? expiresTime = null)
        {
            CookieOptions opt = new CookieOptions();
            if (expiresTime != null)
            {
                opt.Expires = new DateTimeOffset(expiresTime.Value);
            }

            context.Response.Cookies.Append(cookieName, value, opt);
            return value;
        }

        public static void DelCookie(this HttpContext context, string cookieName)
        {
            context.Response.Cookies.Delete(cookieName);
        }

        public static void SetCookieToken(this HttpContext context, string token, DateTime expiresTime)
        {
            SetCookie(context, CommonConfig.THIS.TokenName, token, expiresTime);

        }

        public static void DelCookieToken(this HttpContext context)
        {
            context.Response.Cookies.Delete(CommonConfig.THIS.TokenName);
        }

        public static string GetRemoteIp(this HttpContext context)
        {
            return context.Connection.RemoteIpAddress.ToString();
            //return context.Request.HttpContext.Connection.RemoteIpAddress.ToString();
        }

        public static string GetSession(this HttpContext context, string key, bool isRemove = false)
        {
            string val = context.Session.GetString(key);
            if (isRemove)
            {
                DelSession(context, key);
            }
            return val;
        }

        public static void SetSession(this HttpContext context, string key, string val)
        {
            context.Session.SetString(key, val);
        }

        public static void DelSession(this HttpContext context, string key)
        {
            context.Session.Remove(key);
        }

        /// <summary>
        /// 是否ajax请求，（当前可能仅适用jquery的请求）
        /// </summary>
        public static bool IsAjax(this HttpRequest req)
        {
            bool result = false;

            var xreq = req.Headers.ContainsKey("x-requested-with");
            if (xreq)
            {
                result = req.Headers["x-requested-with"] == "XMLHttpRequest";
            }
            return result;
        }
        /// <summary>
        /// 获取当前请求运行环境服务对象
        /// </summary>
        public static IWebHostEnvironment GetHostingEnvironment(this HttpContext context)
        {
            var env = context.RequestServices.GetService(typeof(IWebHostEnvironment)) as IWebHostEnvironment;
            return env;
        }
        /// <summary>
        /// 获取web静态文件物理路径，如：d:\xxx\项目文件夹\wwwroot
        /// </summary>
        public static string GetWebRootPath(this HttpContext context)
        {
            var env = context.GetHostingEnvironment();
            return env.WebRootPath;
        }
        /// <summary>
        /// 获取项目所在的路径，如：d:\xxx\项目文件夹\
        /// </summary>
        public static string GetContentRootPath(this HttpContext context)
        {
            var env = context.GetHostingEnvironment();
            return env.ContentRootPath;
        }
        /// <summary>
        /// 获取请求的根地址，如：http(s)://localhost:8080
        /// </summary>
        public static string GetRootHost(this HttpContext context)
        {
            return context.Request.IsHttps ? "https://" : "http://" + context.Request.Host.Value;
        }
    }
}